/**
 * 此脚本用于检查foods集合中的categoryId是否与food_categories集合中的ID匹配
 * 检查数据完整性和一致性
 */

const mongoose = require('mongoose');
require('dotenv').config();

// 导入模型定义
const Food = require('../src/models/food.model');
const FoodCategory = require('../src/models/foodCategory.model');

// 连接数据库
mongoose.connect(process.env.MONGODB_URL)
  .then(() => console.log('数据库连接成功'))
  .catch(err => {
    console.error('数据库连接失败:', err);
    process.exit(1);
  });

async function checkCategoryRelations() {
  try {
    console.log('开始检查食物与食物分类的关联...');
    
    // 获取所有食物记录
    const foods = await Food.find().lean();
    console.log(`共找到 ${foods.length} 条食物记录`);
    
    // 获取所有食物分类记录
    const categories = await FoodCategory.find().lean();
    console.log(`共找到 ${categories.length} 条食物分类记录`);
    
    // 创建分类ID映射，用于快速查找
    const categoryIdMap = {};
    categories.forEach(category => {
      categoryIdMap[category._id.toString()] = category.name;
    });
    
    // 检查每个食物的分类ID是否存在
    const problemFoods = [];
    const validFoods = [];
    
    for (const food of foods) {
      const categoryId = food.categoryId ? food.categoryId.toString() : null;
      
      if (!categoryId) {
        problemFoods.push({
          foodId: food._id.toString(),
          foodName: food.name,
          problem: '无分类ID'
        });
        continue;
      }
      
      if (!categoryIdMap[categoryId]) {
        problemFoods.push({
          foodId: food._id.toString(),
          foodName: food.name,
          categoryId: categoryId,
          problem: '分类ID不存在于food_categories集合中'
        });
      } else {
        validFoods.push({
          foodId: food._id.toString(),
          foodName: food.name,
          categoryId: categoryId,
          categoryName: categoryIdMap[categoryId]
        });
      }
    }
    
    // 输出结果
    console.log('\n===== 检查结果 =====');
    console.log(`有效关联: ${validFoods.length} 条食物记录`);
    console.log(`问题关联: ${problemFoods.length} 条食物记录`);
    
    if (problemFoods.length > 0) {
      console.log('\n===== 问题食物列表 =====');
      problemFoods.forEach((food, index) => {
        console.log(`${index + 1}. ${food.foodName} (ID: ${food.foodId})`);
        console.log(`   问题: ${food.problem}`);
        if (food.categoryId) {
          console.log(`   无效的分类ID: ${food.categoryId}`);
        }
        console.log('---');
      });
    } else {
      console.log('\n所有食物都有有效的分类关联，数据一致性良好!');
    }
    
    // 分类统计
    if (validFoods.length > 0) {
      console.log('\n===== 有效分类统计 =====');
      const categoryStats = {};
      validFoods.forEach(food => {
        const catName = categoryIdMap[food.categoryId];
        categoryStats[catName] = (categoryStats[catName] || 0) + 1;
      });
      
      Object.entries(categoryStats)
        .sort((a, b) => b[1] - a[1])
        .forEach(([category, count]) => {
          console.log(`${category}: ${count} 个食物`);
        });
    }
    
    // 检查是否有未使用的分类
    const usedCategoryIds = new Set(validFoods.map(food => food.categoryId));
    const unusedCategories = categories.filter(cat => !usedCategoryIds.has(cat._id.toString()));
    
    if (unusedCategories.length > 0) {
      console.log('\n===== 未使用的分类 =====');
      unusedCategories.forEach(cat => {
        console.log(`${cat.name} (ID: ${cat._id.toString()})`);
      });
    }
    
  } catch (error) {
    console.error('检查过程中发生错误:', error);
  } finally {
    // 关闭数据库连接
    mongoose.connection.close();
    console.log('\n数据库连接已关闭');
  }
}

// 运行检查
checkCategoryRelations(); 